package com.cq.hd.app.biz;

import com.cq.hd.app.dto.IndexPositionDto;
import com.cq.hd.app.vo.IndexPositionVo;
import com.cq.hd.app.vo.MyPageVo;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.GaoDeGeocode;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.utils.AliCloudApiUtils;
import com.cq.hd.common.utils.GaoDeUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.PopRecordApi;
import com.cq.hd.member.api.TbAppUserApi;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.TbBusinessEnterApplyApi;
import com.cq.hd.member.api.dto.PopRecordDto;
import com.cq.hd.member.api.vo.*;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.dto.OrderDto;
import com.cq.hd.order.api.vo.OrderVo;
import com.cq.hd.product.api.TbActiveApi;
import com.cq.hd.system.api.TbHfRegionsApi;
import com.cq.hd.system.api.vo.HfRegionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class IndexBiz {

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbAppUserApi appUserApi;

    @Autowired
    private TbOrderApi orderApi;

    @Autowired
    private TbBusinessEnterApplyApi businessEnterApplyApi;

    @Autowired
    private PopRecordApi popRecordApi;

    @Autowired
    private TbHfRegionsApi hfRegionsApi;

    @Autowired
    private TbActiveApi activeApi;

    public IndexPositionVo position(IndexPositionDto indexPositionDto) {
        IndexPositionVo indexPositionVo = new IndexPositionVo();

//        GaoDeGeocode gaoDeGeocode = GaoDeUtils.degreesToCity(indexPositionDto.getLongitude(), indexPositionDto.getLatitude());
        GaoDeGeocode gaoDeGeocode = AliCloudApiUtils.queryLocation(indexPositionDto.getLongitude(), indexPositionDto.getLatitude());
        if (gaoDeGeocode != null) {
            indexPositionVo.setCountyName(gaoDeGeocode.getCountyName());
            indexPositionVo.setProvince(gaoDeGeocode.getProvince());
            indexPositionVo.setCity(gaoDeGeocode.getCity());
            indexPositionVo.setCountry(gaoDeGeocode.getCountry());
        }
        return indexPositionVo;
    }

    public MyPageVo myPage(AppLoginUser appLoginUser) {
        // 补贴金账户余额（商家显示）
        BigDecimal subsidyAmt = BigDecimal.ZERO;
        // 可提余额（经纪人显示）
        BigDecimal commissionAmt = BigDecimal.ZERO;
        // 今日成交额：今日成交订单金额总和(不包含已退款，包含被分销的订单)；
        BigDecimal orderAmt = BigDecimal.ZERO;
        // 今日成交量：今日成交订单的数量总和(不包含已退款，包含被分销的订单)；
        int orderNum = 0;
        // 今日成交人数：今日成交订单的人数总和(不包含已退款，包含被分销的订单)；
        int orderUserNum = 0;
        // 待支付个数
        int waitPayOrderNum = 0;
        // 待核销个数
        int waitVerifyOrderNum = 0;
        // 商家入驻状态：0-未申请入驻，1-待审核，2-已通过，3-未通过，4-待认证
        int auditState = 0;
        // 商家入驻审核拒绝原因
        String refuseReason = "";
        // 是否要弹窗提示入驻成功
        boolean popState = false;

        Long userId = appLoginUser.getUserId();
        LocalDate now = LocalDate.now();
        String nowStr = LocalDateUtil.toLocalDateToString(now, Constant.YYYY_MM_DD);

        BusinessPageVo businessPageVo = businessApi.getByUserId(userId).unpack();
        if (businessPageVo != null && businessPageVo.getId() != null) {
            subsidyAmt = businessPageVo.getSubsidyAmt();
            auditState = 2;

            // 查询今天商家的订单列表
            OrderDto orderDto = new OrderDto();
            orderDto.setBusinessId(businessPageVo.getId());
            orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(), OrderStateEnum.VERIFYING.getValue(),
                    OrderStateEnum.FINISH.getValue(), OrderStateEnum.VERIFIED.getValue()));
            orderDto.setStartOrderTime(nowStr + " 00:00:00");
            orderDto.setEndOrderTime(nowStr + " 23:59:59");
            List<OrderVo> orderVos = orderApi.listByDto(orderDto).unpack();
            if (!CollectionUtils.isEmpty(orderVos)) {
                for (OrderVo orderVo : orderVos) {
                    // 今日成交额
                    BigDecimal payPrice = orderVo.getPayPrice();
                    orderAmt = orderAmt.add(payPrice);
                }

                // 今日成交量
                orderNum = orderVos.size();

                // 今日成交人数
                orderUserNum = orderVos.stream().map(OrderVo::getUserId).collect(Collectors.toSet()).size();
            }
        } else {
            // 查询商家入驻状态
            BusinessEnterApplyVo businessEnterApplyVo = businessEnterApplyApi.getEnterInfoByUserId(userId).unpack();
            if (businessEnterApplyVo != null) {
                auditState = businessEnterApplyVo.getAuditState();

                if (AuditStateEnum.FAIL.getValue().equals(auditState)) {
                    refuseReason = businessEnterApplyVo.getRefuseReason();
                }

            }
        }

        // 是否是经纪人(1-不是，2-是)
        Integer agentState = appLoginUser.getUserInfo().getAgentState();
        if (agentState != null && agentState == 2) {
            AppUserVo appUserVo = appUserApi.getById(userId).unpack();
            if (appUserVo != null && appUserVo.getId() != null) {
                commissionAmt = appUserVo.getCommissionAmt();
            }
        }

        // 查询待核销（包含核销中）、待支付订单数
        OrderDto orderDto = new OrderDto();
        orderDto.setUserId(userId);
        orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_PAY.getValue(), OrderStateEnum.WAIT_VERIFY.getValue(), OrderStateEnum.VERIFYING.getValue()));
        List<OrderVo> orderVos = orderApi.listByDto(orderDto).unpack();
        if (!CollectionUtils.isEmpty(orderVos)) {
            List<OrderVo> waitPayOrders = orderVos.stream().filter(orderVo -> OrderStateEnum.WAIT_PAY.getValue().equals(orderVo.getOrderState())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(waitPayOrders)) {
                waitPayOrderNum = waitPayOrders.size();
            }

            List<OrderVo> waitVerifyOrders = orderVos.stream().filter(orderVo -> !OrderStateEnum.WAIT_PAY.getValue().equals(orderVo.getOrderState())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(waitVerifyOrders)) {
                waitVerifyOrderNum = waitVerifyOrders.size();
            }
        }

        // 查询弹窗数据
        if (AuditStateEnum.SUCCESS.getValue().equals(auditState)) {
            PopRecordDto popRecordDto = new PopRecordDto();
            popRecordDto.setPlatformType(PlatformTypeEnum.BUSINESS.getValue());
            popRecordDto.setPopType(PopTypeEnum.BUSINESS_ENTER.getValue());
            popRecordDto.setUserId(userId);
            List<PopRecordVo> popRecordVos = popRecordApi.listByDto(popRecordDto).unpack();
            if (CollectionUtils.isEmpty(popRecordVos)) {
                popState = true;
            }
        }

        MyPageVo myPageVo = new MyPageVo();
        myPageVo.setSubsidyAmt(subsidyAmt);
        myPageVo.setCommissionAmt(commissionAmt);
        myPageVo.setOrderAmt(orderAmt);
        myPageVo.setOrderNum(orderNum);
        myPageVo.setOrderUserNum(orderUserNum);
        myPageVo.setWaitPayOrderNum(waitPayOrderNum);
        myPageVo.setWaitVerifyOrderNum(waitVerifyOrderNum);
        myPageVo.setAuditState(auditState);
        myPageVo.setRefuseReason(refuseReason);
        myPageVo.setPopState(popState);

        return myPageVo;
    }

    public List<HfRegionVo> listRegion(String cityName) {
        // 去除空格，换行等
        if (!StringUtils.isBlank(cityName)) {
            cityName = cityName.replaceAll(" ", "").replaceAll("[\\t\\n\\r]", "");
        } else {
            cityName = "";
        }

        Set<String> cityNames = new HashSet<>();
        if (StringUtils.isBlank(cityName)) {
            // 查询已发布活动的城市，包含被删除的数据
            cityNames = activeApi.listCityName().unpack();
        } else {
            cityNames.add(cityName);
        }

        return hfRegionsApi.listHfRegionByCityNames(cityNames).unpack();
    }
}
